/*
 * @Author: luthor luthor-li@qq.com
 * @Date: 2024-10-27 23:21:55
 * @LastEditors: luthor luthor-li@qq.com
 * @LastEditTime: 2024-10-27 23:22:03
 * @FilePath: \tilesethub_back\controllers\authController.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const User = require('../models/user')
const { generateToken } = require('../services/tokenService')

const registerUser = async ctx => {
  const { id, key, allowedTilesets } = ctx.request.body
  const existingUser = await User.findOne({ id })
  if (existingUser) {
    ctx.status = 400
    ctx.body = { message: 'User ID already exists' }
    return
  }
  const newUser = new User({ id, key, allowedTilesets })
  await newUser.save()
  ctx.status = 201
  ctx.body = { message: 'User registered successfully' }
}

const generateTokenForUser = async ctx => {
  const { id, key } = ctx.request.body
  const user = await User.findOne({ id, key })
  if (!user) {
    ctx.status = 401
    ctx.body = { message: 'Invalid credentials' }
    return
  }
  const token = generateToken(user)
  ctx.body = { token }
}

module.exports = { registerUser, generateTokenForUser }
